package com.smashcrush.server.service.impl;

import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.smashcrush.model.Script;
import com.smashcrush.model.ScriptExecutionStatus;
import com.smashcrush.model.ScriptResults;
import com.smashcrush.server.service.TestingService;

@Service
public class TestingServiceImpl implements TestingService {

	private static Log log = LogFactory.getLog(TestingServiceImpl.class);

	Map<String, Script> scripts = new Hashtable<String, Script>();

	Map<String, ScriptResults> results = new Hashtable<String, ScriptResults>();

	@Override
	public void pushScript(String token, Script script) {
		ScriptResults pollResults = new ScriptResults();
		pollResults.setPollResultsStatus(ScriptExecutionStatus.SendToDesktop);
		results.put(token, pollResults);

		scripts.put(token, script);
	}

	@Override
	public Script pollScript(String token) {

		return scripts.remove(token);
		
//		Script script = null;
//
//		// TODO: Implement real async comet for performance
//		while (true) {
//			log.debug("pollScript");
//			script = scripts.remove(token);
//			System.out.println("Script? " + (script));
//			if (script == null) {
//				try {
//					Thread.sleep(5000);
//				} catch (InterruptedException e) {
//					log.error("pollScript interrupted");
//					throw new RuntimeException(e);
//				}
//			} else {
//				results.get(token).setPollResultsStatus(
//						PollResultsStatus.ExecutingScript);
//				break;
//			}
//		}
//
//		return script;
	}

	@Override
	public ScriptResults pollResults(String token) {

		return results.get(token);
//		result.wait();
//
//		// TODO: Implement real async comet for performance
//		while (true) {
//			result = results.get(token);
//			if (result.getResults() == null) {
//				try {
//					Thread.sleep(5000);
//				} catch (InterruptedException e) {
//					throw new RuntimeException(e);
//				}
//			} else {
//				break;
//			}
//		}
//
//		return result;
	}

	@Override
	public void pushResults(String token, Map<String, String> result) {
		ScriptResults resultz = results.get(token);
		resultz.setResults(result);
		resultz.setPollResultsStatus(ScriptExecutionStatus.Done);
		resultz.notify();
	}

}
